package com.general.framework.job.starter;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Job自动配置类
 */
@Slf4j
@Configuration
@ConditionalOnClass(XxlJobSpringExecutor.class)
@ConditionalOnProperty(prefix = "com.chushouya.job", name = "enable", havingValue = "true")
@EnableConfigurationProperties({JobProperties.class})
public class JobAutoConfiguration {

    private final static String DEFAULT_LOG_PATH = "/data/logs/xxl-job/";

    @Bean
    @ConditionalOnClass(XxlJobSpringExecutor.class)
    public XxlJobSpringExecutor xxlJobExecutor(final JobProperties jobProperties) {
        log.info(">>>>>>>>>>> chushouya-job config init...");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAccessToken(jobProperties.getAccessToken());
        xxlJobSpringExecutor.setAdminAddresses(jobProperties.getServer());

        JobProperties.Executor executor = jobProperties.getExecutor();
        if (executor == null) {
            return xxlJobSpringExecutor;
        }
        xxlJobSpringExecutor.setAppname(executor.getName());
        xxlJobSpringExecutor.setAddress(executor.getAddress());
        xxlJobSpringExecutor.setIp(executor.getIp());
        xxlJobSpringExecutor.setPort(executor.getPort() == null ? 0 : executor.getPort());
        xxlJobSpringExecutor.setLogPath(executor.getLogPath());
        if (executor.getLogPath() == null) {
            xxlJobSpringExecutor.setLogPath(DEFAULT_LOG_PATH + executor.getName());
        }
        // 日志保留天数
        xxlJobSpringExecutor.setLogRetentionDays(executor.getLogDays() == null ? 30 : executor.getLogDays());
        return xxlJobSpringExecutor;
    }
}
